package com.jcode222.controller;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jcode222.entity.User;
import com.jcode222.mappings.UserMapping;
import com.jcode222.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @ApiOperation("根据ID查询用户")
    @GetMapping("/get/{id}")
    public String getUser(@PathVariable("id") Long id) {
        return JSON.toJSONString(userService.getById(id));
    }

    @ApiOperation("根据ID查询用户DTO")
    @GetMapping("/get/dto/{id}")
    public String getUserDto(@PathVariable("id") Long id) {
        return UserMapping.INSTANCE.userToUserDto(userService.getById(id)).toString();
    }

    // 查询所有用户
    @ApiOperation("查询所有用户")
    @GetMapping("/get/all")
    public String getAllUsers() {
        return userService.list().toString();
    }

    // 新增用户
    @ApiOperation("新增用户")
    @PostMapping("/add")
    public String addUser(User user) {
        return JSON.toJSONString(userService.save(user));
    }

    // 分页查询
    @ApiOperation("分页查询用户")
    @GetMapping("/page")
    public String getPageUsers(Integer pageNum, Integer pageSize) {
        return JSON.toJSONString(userService.page(new Page<>(pageNum, pageSize)));
    }

    // 批量插入
    @ApiOperation("批量插入用户")
    @GetMapping("/batch/add")
    public String batchAddUsers() {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int nextInt = RandomUtils.nextInt();
            User newUser = new User();
            newUser.setName("user" + nextInt);
            newUser.setAge(nextInt);
            users.add(newUser);
        }
        boolean batch =  userService.saveBatch(users);
        return JSON.toJSONString(batch);
    }
}
